using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Globalization;
using Microsoft.SharePoint.Navigation;

namespace DMS.Features.DMSBranding
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("463bab91-6d59-4f74-bd4f-b11e019f9eac")]
    public class DMSBrandingEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        /// <summary>
        /// Create Sites: Invoices Root Site, GATs, CreditApplications, and Search Site
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite featureSite = properties.Feature.Parent as SPSite;
            using (SPSite site = new SPSite(featureSite.ID))
            {

                //create subsites
                SPWeb rootWeb = site.RootWeb;
                string invoiceSite = "Invoices";
                string gatsSite = "GATs";
                string creditApplication = "CreditApplications";
                string searchSite = "Search";
                string receiptSite = "Receipts";
                string docsboxSite = "Docsbox";


                if (!IsSubsiteExist(rootWeb, invoiceSite))
                    CreateSubSite(rootWeb.Url, invoiceSite, "Invoices", "STS#0",true);



                ////////////////////Create Invoices Site For Current Year (2012)///////////////
                //SPWeb invoiceWeb = rootWeb.Webs["invoices"];
                //string currentYear = DateTime.Now.Year.ToString();
                //if (!IsSubsiteExist(invoiceWeb, currentYear))
                //    CreateSubSite(rootWeb.Url, "invoices", currentYear, currentYear, "STS#0");
                //////////////////////////////////////////////////////////////////////////////




                if (!IsSubsiteExist(rootWeb, gatsSite))
                    CreateSubSite(rootWeb.Url, gatsSite, "GATs", "STS#0",true);

                if (!IsSubsiteExist(rootWeb, creditApplication))
                    CreateSubSite(rootWeb.Url, creditApplication, "Credit Applications", "STS#0",true);

                if (!IsSubsiteExist(rootWeb, searchSite))
                    CreateSubSite(rootWeb.Url, searchSite, "Search Center", "SRCHCENTERLITE#0",false);

                if (!IsSubsiteExist(rootWeb, receiptSite))
                    CreateSubSite(rootWeb.Url, receiptSite, "Receipts", "STS#0", true);

                if (!IsSubsiteExist(rootWeb, docsboxSite))
                    CreateSubSite(rootWeb.Url, docsboxSite, "Docsbox", "STS#0", true);

                string rootWebRelativePath = rootWeb.ServerRelativeUrl;
                if (!rootWebRelativePath.EndsWith("/"))
                    rootWebRelativePath += "/";
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    foreach (SPWeb web in site.AllWebs)
                    {
                        web.SiteLogoUrl = rootWebRelativePath + "Images/turnerslogo.jpg";
                        web.UIVersion = 4;
                        web.Update();
                    }
                });
            }
        }

        private bool IsSubsiteExist(SPWeb rootWeb, string invoiceSite)
        {
            if (rootWeb.Webs[invoiceSite].Exists)
                return true;
            return false;
        }

        private string CreateSubSite(string rootWebUrl, string subsiteUrl, string siteTitle, string siteTemplateName, bool showInTopNavigationBar)
        {
            const Int32 LOCALE_ID_ENGLISH = 1033;
            string newSiteUrl = string.Empty;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite siteCollection = new SPSite(rootWebUrl))
                    {
                        using (SPWeb rootWeb = siteCollection.RootWeb)
                        {
                            SPWebTemplateCollection templates = rootWeb.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));
                            SPWebTemplate siteTemplate = templates[siteTemplateName];

                            SPNavigationNodeCollection topNav = rootWeb.Navigation.TopNavigationBar;

                            using (SPWeb newSite = rootWeb.Webs.Add(subsiteUrl, siteTitle, "", Convert.ToUInt32(LOCALE_ID_ENGLISH), siteTemplate, false, false))
                            {
                                if (!string.IsNullOrEmpty(newSite.Url))
                                {
                                    newSiteUrl = newSite.Url;
                                    if (showInTopNavigationBar)
                                    {
                                        string linkTitle = newSite.Title;
                                        if (linkTitle.Length > 25)
                                            linkTitle = linkTitle.Substring(0, 23) + "...";
                                        SPNavigationNode node = rootWeb.Navigation.GetNodeByUrl(newSite.ServerRelativeUrl);
                                        if(node == null)
                                        {
                                            node = new SPNavigationNode(linkTitle, newSite.ServerRelativeUrl);

                                            node = topNav.AddAsLast(node);
                                            node.Update();
                                        }
                                    }
                                }
                                newSite.Navigation.UseShared = true;
                            }
                        }
                    }

                });
                return newSiteUrl;
            }
            catch (Exception)
            {

                throw;
            }
        }


        private string CreateSubSite(string rootWebUrl, string parentSitePath, string subsiteUrl, string siteTitle, string siteTemplateName)
        {
            const Int32 LOCALE_ID_ENGLISH = 1033;
            string newSiteUrl = string.Empty;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite siteCollection = new SPSite(rootWebUrl))
                    {
                        using (SPWeb rootWeb = siteCollection.OpenWeb(parentSitePath))
                        {
                            SPWebTemplateCollection templates = rootWeb.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));
                            SPWebTemplate siteTemplate = templates[siteTemplateName];

                            using (SPWeb newSite = rootWeb.Webs.Add(subsiteUrl, siteTitle, "", Convert.ToUInt32(LOCALE_ID_ENGLISH), siteTemplate, false, false))
                            {

                                if (!string.IsNullOrEmpty(newSite.Url))
                                    newSiteUrl = newSite.Url.ToString();
                            }
                        }
                    }

                });
                return newSiteUrl;
            }
            catch (Exception)
            {

                throw;
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{


        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
